<%@page import="org.firestorm.traficforecast.database.User"%>
<%@page import="java.util.HashMap"%>
<%@page import="org.firestorm.traficforecast.utils.Md5"%>
<%@page import="org.firestorm.traficforecast.utils.Constant"%>
<%@page import="org.firestorm.traficforecast.database.UserDAO"%>
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
	request.setCharacterEncoding("utf8");
	response.setContentType("application/json");
	PrintWriter outt = response.getWriter();

	String id = request.getParameter("id");
	if ("login".equals(id)) {
		String page_ = request.getParameter("p");
		if ("admin".equals(page_)) {
			JSONObject jsonObj = (JSONObject) JSONValue.parse(request
					.getParameter("para"));
			String username = jsonObj.get("user").toString();
			if("admin".equals(username)){
				String password = Md5.Hash(jsonObj.get("pass").toString());
				int result = UserDAO.checkLogin(username, password);
				JSONObject obj;
				if (result == Constant.LOGIN_SUCCESS) {
					HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
					tmp.put("res", true);
					obj = new JSONObject(tmp);
					User user = UserDAO.getUser(username, password);
					session.setAttribute("user", user);
					obj = new JSONObject(tmp);
				} else {
					HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
					tmp.put("res", false);
					obj = new JSONObject(tmp);
				}
				out.print(obj);
			}else{
				HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
				tmp.put("res", false);
				JSONObject obj = new JSONObject(tmp);
				out.print(obj);
			}
		} else {
			JSONObject jsonObj = (JSONObject) JSONValue.parse(request
					.getParameter("para"));
			String username = jsonObj.get("user").toString();
			String password = Md5.Hash(jsonObj.get("pass").toString());
			int result = UserDAO.checkLogin(username, password);
			JSONObject obj;
			if (result == Constant.LOGIN_SUCCESS) {
				HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
				tmp.put("res", true);
				obj = new JSONObject(tmp);
				User user = UserDAO.getUser(username, password);
				session.setAttribute("user", user);
				obj = new JSONObject(tmp);
			} else {
				HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
				tmp.put("res", false);
				obj = new JSONObject(tmp);
			}
			out.print(obj);
		}
	} else if ("logout".equals(id)) {
		session.removeAttribute("user");
		HashMap<String, Boolean> tmp = new HashMap<String, Boolean>();
		tmp.put("res", true);
		JSONObject obj = new JSONObject(tmp);
		out.print(obj);
		out.flush();
	}
%>